package com.smiiler.skin.haoyaoshi;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.smiier.skin.util.GlobalSettings;

import android.util.Log;

public class ParamsEncrypt {

	private static String getParamStr(String[] arr, Map paramMap) {
		StringBuilder sb = new StringBuilder();
		if (arr != null && arr.length > 0) {
			for (int i = 0; i < arr.length; i++) {
				sb.append(arr[i] + paramMap.get(arr[i]));
			}
		}
		return sb.toString();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, String> convertRequestParamMap(Map parameterMap) {
		Map<String, String> paramMap = null;
		if (parameterMap != null && parameterMap.size() > 0) {
			Iterator it = parameterMap.entrySet().iterator();
			paramMap = new HashMap();
			while (it.hasNext()) {
				Map.Entry entry = (Map.Entry) it.next();
				Object obj = entry.getValue();
				String entryKye = (String) entry.getKey();
				if ("sign".equalsIgnoreCase(entryKye)) {
					continue;// signֵ��������֤
				}
				String val = "";
				if (obj instanceof String[]) {
					String[] strs = (String[]) obj;
					for (int i = 0; i < strs.length; i++) {
						val += strs[i];
					}
				} else {
					val = obj.toString();
				}
				paramMap.put(entryKye, val);
			}
		}
		return paramMap;
	}

	public static String generateSign(String testSecureKye,
			String interFaceName, Map<String, String[]> parameterMap) {

		Map<String, String> newParamMap = convertRequestParamMap(parameterMap);
		/*
		 * if(newParamMap == null){ logging.error("�������������Ϊ�գ�����ϵ�������̼�����Ա��" );
		 * throw new BusinessException("���������������Ϊ�գ�����ϵ�������̼�����Ա��"); }
		 */
		String[] ucParamArr = null;
		Set<String> newParamSet = newParamMap.keySet();
		ucParamArr = newParamSet.toArray(new String[newParamSet.size()]);
		// �������������
		Arrays.sort(ucParamArr);
		String sortedParam = getParamStr(ucParamArr, newParamMap);
		/*
		 * if(interFaceName == null || "".equals(interFaceName)){
		 * logging.error("�������̵��õ�APIΪ�գ�" ); throw new
		 * BusinessException("�������̵��õ�APIΪ��"); }
		 * 
		 * if(testSecureKye == null || "".equals(testSecureKye)){
		 * logging.error("�������̰�ȫkeyΪ��" ); throw new
		 * BusinessException("��������IDΪ��"); }
		 */

		// ��������ǰ���ַ�api+����+��ȫkey
		StringBuilder waitingEncrypStringSB = new StringBuilder();
		waitingEncrypStringSB.append(interFaceName).append(sortedParam)
				.append(testSecureKye);
		// ����Md5����
		// logging.debug("����ǰ�ַ�"+waitingEncrypStringSB.toString());

		Log.i("testhaoyaoshi", "����ǰ�ַ�" + waitingEncrypStringSB.toString());
		String encryptionStr = EncoderHandler.encode("SHA1",
				waitingEncrypStringSB.toString());

		return encryptionStr;
	}
	
	
}
